#include "offline_message_count_request.h"

#include <iostream>
#include <sstream>
#include <string>
#include <map>

#include "base/logging.h"
#include "base/json_escape.h"

namespace imserver {
namespace fcgi {

bool OfflineMessageCountRequest::Response() {
  if (!fcgi_out_) {
    LOG_WARN("null fcgi_out!");
    return false;
  }
  ParseUserIdentity();

  int message_count = 0, result = 0;
  MessageResult res;
  if (effective_id() > 0) {
    result = MessageHistoryAdapter::Instance().GetOfflineMessageCount(effective_id(), &message_count, 2);
    LOG_INFO("GetOfflineMessageCount uid=" << effective_id() << " Count=" << message_count);
  } else {
    LOG_WARN("GetOfflineMessages bad param, uid=" << effective_id());
    result = -3;
  }

  std::stringstream rsp_header;
  rsp_header << "Content-type: text/javascript; charset=utf-8\r\n" << "\r\n";
  FCGX_PutS(rsp_header.str().c_str(), fcgi_out_);

  std::stringstream rsp_body;

  if (message_count > 0) {
    rsp_body << "{\"code\":" << 1 << ",\"msgnum\":" << message_count << "}";
  } else {
    rsp_body << "{\"code\":" << result << "}";
  }

  LOG_DEBUG("OfflineMessageRequest rsp=" << rsp_body.str() << " result=" << result);

  FCGX_PutS(rsp_body.str().c_str(), fcgi_out_);
  return true;
}

}
}


